package com.starlink.service.impl;

import com.starlink.common.enums.ErrorCode;
import com.starlink.common.utils.AssertUtil;
import com.starlink.mapper.AdminMapper;
import com.starlink.mapper.AdminRoleMapper;
import com.starlink.mapper.PermissionMapper;
import com.starlink.mapper.RolePermissionMapper;
import com.starlink.model.domain.AdminDO;
import com.starlink.model.domain.PermissionDO;
import com.starlink.model.domain.RoleDO;
import com.starlink.model.dtomapper.AdminDtoMapper;
import com.starlink.model.vo.AdminVO;
import com.starlink.service.AdminAccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 管理员
 */
@Slf4j
@Service
public class AdminAccountServiceImpl implements AdminAccountService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 查询管理员
     *
     * @param account  账号
     * @param password 密码
     * @return
     */
    @Override
    public AdminVO findAdmin(String account, String password) {
        AdminDO admin = adminMapper.findByCondition(account, password);
        AssertUtil.assertNotNull(admin, ErrorCode.USER_OR_PWD_INVALID);
        /** 获取权限 */
        Set<PermissionDO> permissionSet = new HashSet<>();
        List<RoleDO> roles = adminRoleMapper.findByAdminId(admin.getId());
        for (RoleDO role : CollectionUtils.emptyIfNull(roles)) {
            List<PermissionDO> permissions = rolePermissionMapper.findByRoleId(role.getId());
            for (PermissionDO permission : CollectionUtils.emptyIfNull(permissions)) {
                if (permission.getParentId() != 0) {
                    //兼容处理多层级前端半选的情况
                    PermissionDO parent = permissionMapper.findById(permission.getParentId());
                    permissionSet.add(parent);
                }
                permissionSet.add(permission);
            }
        }
        List<String> permissionCodes = permissionSet.stream().sorted(Comparator.comparing(PermissionDO::getId)).map(PermissionDO::getCode).collect(Collectors.toList());

        AdminVO adminVO = AdminDtoMapper.INSTANCE.do2VO(admin);
        adminVO.setPermissionCodes(permissionCodes);
        return adminVO;
    }

    /**
     * 根据id查询admin
     */
    @Override
    public AdminVO queryById(long adminId) {
        return AdminDtoMapper.INSTANCE.do2VO(adminMapper.findById(adminId));
    }

}
